<template>
	<div class="lc_wrap">
		<el-row class="trendanalysis">
			<el-col :span="leftWidth">
				<div class="box treeBox">
					<basic-container>
						<lcTree @ready="ready" :deviceType='deviceType'></lcTree>
					</basic-container>
				</div>
			</el-col>
			<el-col :span="rightWidth" class="table-wrapper" style="position: relative">
				<overlay @changeTreeBox="changeTreeBox"></overlay>
				<basic-container>
					<div class="search-tools">
						<div class="search-left">
							<!-- 时 -->
							<div v-if="dateType==1">
								<el-date-picker v-model="dateTime" type="date" size="small" value-format="yyyy-MM-dd" :picker-options="pickerOption" placeholder="选择日期" :clearable='false'></el-date-picker>
								<el-time-select v-model="hourTime" size="small" placeholder="选择时间" :picker-options="{
                                    start: '00:00',
                                    step: '01:00',
                                    end: '23:00'
                                }" :clearable="false" style="margin-left:10px"></el-time-select>
							</div>
							<!-- 日 -->
							<div v-if="dateType==2">
								<el-date-picker v-model="dateTime" type="date" size="small" value-format="yyyy-MM-dd" :picker-options="pickerOption" placeholder="选择日期" :clearable='false'></el-date-picker>
							</div>
							<!-- 周 -->
							<div v-if="dateType==3">
								<el-date-picker v-model="dateTime" type="week" size="small" format="yyyy 第 WW 周" value-format="yyyy-MM-dd" :picker-options="pickerOption" placeholder="选择周" :clearable='false'></el-date-picker>
							</div>
							<!-- 月 -->
							<div v-if="dateType==4">
								<el-date-picker v-model="dateTime" type="month" size="small" value-format="yyyy-MM" :picker-options="pickerOption" placeholder="选择月份" :clearable='false'></el-date-picker>
							</div>
							<!-- 年 -->
							<div v-if="dateType==5">
								<el-date-picker v-model="dateTime" type="year" size="small" value-format="yyyy" :picker-options="pickerOption" placeholder="选择年份" :clearable='false'></el-date-picker>
							</div>
						</div>
						<div class="search-right">
							<div class="search-tabs">
								<el-radio v-model="dateType" v-for="(item, index) in dateTypeList" :key="index" :label="item.id" :disabled="item.disable">{{ item.value }}
								</el-radio>
							</div>
							<div class="searcg-btns">
								<el-button type="primary" size="small" icon="el-icon-search" @click="search">搜 索</el-button>
							</div>
						</div>
					</div>

					<noData v-if="isEmpty"></noData>
					<e-chart autoresize :options="chartOptions" style="height:30%;"></e-chart>
					<e-chart autoresize :options="chartOptionsOther" style="height:30%;" v-if="chartOptionsOtherShow"></e-chart>
					<e-chart id="echartss" autoresize :options="chartOptionsWind" style="height:30%;"></e-chart>
				</basic-container>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	import { getDeptTree, getTypes, getLine, getFactorList, getWind } from "@/api/airq/trendanalysis";
	import { mapGetters } from "vuex";
	import { dateFormat } from "@/util/date";
	import lcCheckBoxTree from "@/components/common/tree_checkBox.vue";
	import lcTree from "@/components/common/tree.vue";
	import noData from "@/components/common/noData";
	import echarts from "echarts";
	import overlay from "@/components/common/overlay.vue";
	export default {
		components: {
			lcCheckBoxTree,
			lcTree,
			noData,
			overlay
		},
		data() {
			let _this = this
			return {
				chartOptionsOtherShow: true,
				isEmpty: true,
				chartOptions: {},
				chartOptionsOther: {},
				chartOptionsWind: {},
				leftWidth: this.$leftWidth,
				rightWidth: this.$rightWidth,
				data: [],
				deptInfoName: '',
				deptInfoId: '',
				dateType: '', // 日期格式：日、月、年
				// dateTime: dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss'),
				dateTime: dateFormat(new Date(), 'yyyy-MM-dd'), // 默认显示的日期
				dateTime2: '',
				hourTime: '00:00',
				dateTypeList: [],
				pickerOption: {
					firstDayOfWeek: 1,
					disabledDate(time) {
						return _this.dateType == 3 ? false : time.getTime() > Date.now()
					},
				},
				nodeList: [], // 存放已勾选节点value的数组（底层节点
				geneList: [],
				gene: '',
				unit: '',
				t2: null,
				interval: 59,
				rowData: {
					"data": [{
							"time": "2020-11-24T00:00:00",
							"windSpeed": 9,
							"windDirection": "西风",
							"waveHeight": 2.64
						},
						{
							"time": "2020-11-24T01:00:00",
							"windSpeed": 10,
							"windDirection": "西南风",
							"waveHeight": 2.57
						},
						{
							"time": "2020-11-24T02:00:00",
							"windSpeed": 12,
							"windDirection": "南风",
							"waveHeight": 2.49
						},
						{
							"time": "2020-11-24T03:00:00",
							"windSpeed": 12,
							"windDirection": "东南风",
							"waveHeight": 2.44
						},
						{
							"time": "2020-11-24T04:00:00",
							"windSpeed": 11,
							"windDirection": "东风",
							"waveHeight": 2.38
						},
						{
							"time": "2020-11-24T05:00:00",
							"windSpeed": 10,
							"windDirection": "东北风",
							"waveHeight": 2.34
						},
						{
							"time": "2020-11-24T06:00:00",
							"windSpeed": 10,
							"windDirection": "北风",
							"waveHeight": 2.34
						},
						{
							"time": "2020-11-24T07:00:00",
							"windSpeed": 10,
							"windDirection": "西北风",
							"waveHeight": 2.34
						},
					]
				}
			};
		},
		computed: {
			...mapGetters(["permission"]),
		},
		mounted() {

		},
		watch: {
			filterText(val) {
				this.$refs.tree.filter(val);
			},
			dateType() {
				this.dateTime = dateFormat(new Date(), 'yyyy-MM-dd') // 默认显示的日期
			},
		},
		methods: {
			/**左侧树加载完毕时间**/
			ready(val) {
				if(val.nodeType >= 2) {
					this.nodeId = val.key;
					this.deptInfoName = val.title;
					this.deptInfoId = val.key;
					this.dateTime = dateFormat(new Date(), 'yyyy-MM');
					let that = this;
					that.onLoad();
				} else {
					return false
				}

			},
			getDateTime2() {
				let myDate = null
				switch(this.dateType) {
					case 1: // 时
						myDate = this.dateTime.slice(0, 10) + ' ' + this.hourTime.slice(0, 2)
						break;
					case 2: // 日
						myDate = this.dateTime.slice(0, 10)
						this.interval = 59
						break;
					case 3: // 周
						myDate = this.dateTime.slice(0, 10)
						break;
					case 4: // 月
						myDate = this.dateTime.slice(0, 7)
						this.interval = 0
						break;
					case 5: // 年
						myDate = this.dateTime.slice(0, 4)
						this.interval = 0
						break;
					default:
						myDate = this.dateTime
						break;
				}
				this.dateTime2 = myDate;
			},
			onLoad() {
				this.getDateTime2()
				/**日期types 日 月 年**/
				getTypes().then(res => {
					this.dateTime = dateFormat(new Date(), 'yyyy-MM-dd')
					this.dateTypeList = res.data.data;
					this.dateType = this.dateTypeList[0].id; //默认第一个日
					this.getLineInfo() //
				})
			},
			getLineInfo() {
				if(this.dateType == 2) {
					this.dateTime2 = dateFormat(new Date(), 'yyyy-MM-dd')
				}
				/**风速**/
				getWind(this.nodeId, this.dateTime, this.dateType).then(res => {
					this.chartOptionsWind = {} //如果没有加载到数据 置空风向
					if(res.data.data.length > 0) {
						let rawData = res.data.data					
						var directionMap = {};
						var arr = ['东风', '东北风', '北风', '西北风', '西风', '西南风', '南风', '东南风']
						echarts.util.each(
							arr,
							function(name, index) {
								directionMap[name] = Math.PI / 4 * (index + 7); //方向箭头偏离了方向 所以用+7
							}
						);
						var data = echarts.util.map(rawData, function(entry) {
							return [entry.time, entry.windSpeed, entry.windDirection];
						});
						var dims = {
							time: 0,
							windSpeed: 1,
							windDirection: 2,
						};
						var arrowSize = 18;

						function renderArrow(param, api) {
							var point = api.coord([
								api.value(dims.time),
								api.value(dims.windSpeed)
							]);
							return {
								type: 'path',
								shape: {
									pathData: 'M1023.90001 0.09999L0 513.049897 398.161117 624.938971l110.989161 399.061029z',
									x: -arrowSize / 2,
									y: -arrowSize / 2,
									width: arrowSize,
									height: arrowSize
								},
								rotation: directionMap[api.value(dims.windDirection)],
								position: point,
								style: api.style({
									stroke: '#555',
									lineWidth: 1
								})
							};
						}

						this.chartOptionsWind = {
							tooltip: {
								trigger: 'axis',
								formatter: function(params) {
									
									return [
										echarts.format.formatTime('yyyy-MM-dd', params[0].value[dims.time]) +
										' ' + echarts.format.formatTime('hh:mm', params[0].value[dims.time]),
										'风速：' + params[0].value[dims.windSpeed] + 'm/s',
										'风向：' + params[0].value[dims.windDirection]
									].join('<br>');
								}
							},
							grid: {},
							xAxis: {
								type: 'time',
							},
							yAxis: [{
								name: '风速（m/s）',
								nameLocation: 'middle',
								nameGap: 35,
								axisLine: {
									lineStyle: {
										color: '#666'
									}
								},
								splitLine: {
									lineStyle: {
										color: '#ddd'
									}
								}
							}, {
								axisLine: {
									show: false
								},
								axisTick: {
									show: false
								},
								axisLabel: {
									show: false
								},
								splitLine: {
									show: false
								}
							}],
							visualMap: {
								type: 'piecewise',
								orient: 'horizontal',
								left: 'center',
								bottom: 0,
								pieces: [
								{
									gte:0.0,
									lte: 0.2,
									color: '#d9e5ff',
									label: '无风（0~0.2）'
								},
								{
									gte:0.2,
									lte: 10.7,
									color: '#ADC6FF',
									label: '微风（0.3~10.7）'
								},
								{
									gte:10.8,
									lte: 13.8,
									color: '#7B99FA',
									label: '强风（10.8~13.8）'
								},
								{
									gte:13.9,
									lte: 17.1,
									color: '#2c97ef',
									label: '劲风（13.9~17.1）'
								},	
								{
									gte:17.2,
									lte: 20.7,
									color: '#10c697',
									label: '大风（17.2~20.7）'
								},
								{
									gte:20.8,
									lte: 24.4,
									color: '#f2d000',
									label: '烈风（20.8~24.4）'
								},
								{
									gte:24.5,
									lte: 28.4,
									color: '#ea7800',
									label: '狂风（24.5~28.4）'
								},	
								{
									gte:28.5,
									lte: 32.6,
									color: '#a8000a',
									label: '暴风（28.5~32.6）'
								}								
								],
								seriesIndex: 1,
								dimension: 1
							},
							series: [{
								type: 'line',
								yAxisIndex: 1,
								showSymbol: false,
								hoverAnimation: false,
								symbolSize: 10,
								smooth: true,
								lineStyle: {
									normal: {
										color: '#96c533'
									}
								},
								itemStyle: {
									normal: {
										color: 'rgba(88,160,253,1)'
									}
								},
								encode: {
									x: dims.time,
									y: dims.waveHeight
								},
								data: data,
								z: 2
							}, {
								type: 'custom',
								renderItem: renderArrow,
								encode: {
									x: dims.time,
									y: dims.windSpeed
								},
								data: data,
								z: 10
							}]
						}
					}
				})

				/**折线**/
				getLine(this.nodeId, this.dateTime, this.dateType).then(res => {
					const resData = res.data.data
					this.chartOptions = {}
					this.chartOptionsOther = {}
					if(res.data.data.length > 0) {
						this.isEmpty = false //暂无数据隐藏
						this.chartOptions = {
							tooltip: {
								trigger: 'axis',
								axisPointer: { // 坐标轴指示器，坐标轴触发有效
									type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
								},
								formatter: function(params, ticket, callback) {
									var htmlStr = '';
									for(var i = 0; i < params.length; i++) {
										var param = params[i];
										var xName = param.name; //x轴的名称
										var seriesName = param.seriesName.split('-')[0]; //图例名称
										var value = param.value + ' ' + param.seriesName.split('-')[1]; //y轴值
										var color = param.color; //图例颜色
										if(i === 0) {
											htmlStr += xName + '<br/>'; //x轴的名称
										}
										htmlStr += '<div>';
										//为了保证和原来的效果一样，这里自己实现了一个点的效果
										htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>';
										// 文本颜色设置--2020-07-23(需要设置,请解注释下面一行)
										//htmlStr += '<span style="color:'+color+'">';
										//圆点后面显示的文本
										htmlStr += seriesName + '：' + value;
										// 文本颜色设置--2020-07-23(需要设置,请解注释下面一行)
										//htmlStr += '</span>';
										htmlStr += '</div>';
									}
									return htmlStr;
								}
							},
							// color: '#1148ff',
							legend: {
								data: [],
								formatter: function(params) {
									let arr = params.split('-')
									return arr[0]
								}
							},
							grid: {
								left: '3%',
								right: '4%',
								bottom: '3%',
								containLabel: true
							},
							xAxis: [{
								type: 'category',
								data: [],
								axisLabel: {
									interval: this.interval, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
									color: '#ccc'
								},
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false
							}],
							yAxis: {
								type: 'value',
								// axisLabel: {
								//   formatter: '{value} ' + this.unit,
								//   color: '#333',
								// },
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false,
								splitLine: {
									show: true,
									lineStyle: {
										color: '#374062',
										type: 'dashed' //设置背景为虚线
									}
								}
							},
							series: []
						}
						this.chartOptionsOther = {
							tooltip: {
								trigger: 'axis',
								axisPointer: { // 坐标轴指示器，坐标轴触发有效
									type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
								},
								formatter: function(params, ticket, callback) {
									var htmlStr = '';
									for(var i = 0; i < params.length; i++) {
										var param = params[i];
										var xName = param.name; //x轴的名称
										var seriesName = param.seriesName.split('-')[0]; //图例名称
										var value = param.value + ' ' + param.seriesName.split('-')[1]; //y轴值
										var color = param.color; //图例颜色
										if(i === 0) {
											htmlStr += xName + '<br/>'; //x轴的名称
										}
										htmlStr += '<div>';
										//为了保证和原来的效果一样，这里自己实现了一个点的效果
										htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>';
										// 文本颜色设置--2020-07-23(需要设置,请解注释下面一行)
										//htmlStr += '<span style="color:'+color+'">';
										//圆点后面显示的文本
										htmlStr += seriesName + '：' + value;
										// 文本颜色设置--2020-07-23(需要设置,请解注释下面一行)
										//htmlStr += '</span>';
										htmlStr += '</div>';
									}
									return htmlStr;
								}
							},
							// color: '#1148ff',
							legend: {
								data: [],
								formatter: function(params) {
									let arr = params.split('-')
									return arr[0]
								}
							},
							grid: {
								left: '3%',
								right: '4%',
								bottom: '3%',
								containLabel: true
							},
							xAxis: [{
								type: 'category',
								data: [],
								axisLabel: {
									interval: this.interval, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
									color: '#ccc'
								},
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false
							}],
							yAxis: {
								type: 'value',
								axisLabel: {
									formatter: '{value} ' + this.unit,
									color: '#333',
								},
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false,
								splitLine: {
									show: true,
									lineStyle: {
										color: '#374062',
										type: 'dashed' //设置背景为虚线
									}
								}
							},
							series: []
						}
						this.chartOptions.xAxis[0].data = res.data.data[0].xarray; //x轴数据

						this.chartOptionsOther.xAxis[0].data = res.data.data[0].xarray; //x轴数据
						res.data.data.map((item, ind) => {
							//|| item.factorName == 'AQI'
							if(item.factorName == 'NO₂' || item.factorName == 'O₃' || item.factorName == 'CO' || item.factorName == 'PM10' || item.factorName == 'PM2.5' || item.factorName == 'SO₂') {
								this.chartOptions.series.push({
									data: item.yarray,
									type: 'line',
									smooth: 0.5,
									// name: item.factorName
									name: item.factorName + '-' + item.unit
								})
								this.chartOptions.legend.data.push(item.factorName + '-' + item.unit)
							}
							if(item.factorName == '温度' || item.factorName == '湿度' || item.factorName == '气压') {
								this.chartOptionsOther.series.push({
									data: item.yarray,
									type: 'line',
									smooth: 0.5,
									areaStyle: {}, //折线图堆叠
									// name: item.factorName,
									name: item.factorName + '-' + item.unit
								})

								this.chartOptionsOther.legend.data.push(item.factorName + '-' + item.unit)
							}
						})
						if(this.chartOptionsOther.series.length == 0) {
							this.chartOptionsOtherShow = false
						}else{
							this.chartOptionsOtherShow = true
						}

					}
				})
			},
			getFactorList() {
				if(this.nodeList.length == 0) {
					this.isEmpty = true //如果没有选中 则暂无数据
					this.chartOptions = {}
					return
				}
				getFactorList(this.nodeList.join(',')).then(res => {
					this.geneList = res.data.data;
					this.gene = this.geneList[0].factorCode;
					this.unit = this.geneList[0].unit
				}).then(() => {

					this.getLine()
				})
			},

			changeTreeBox() {
				this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
				this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
			},
			// 搜索
			search() {
				for(var i = 0; i < this.geneList.length; i++) {
					if(this.gene == this.geneList[i].factorCode) {
						this.unit = this.geneList[i].unit
						break;
					}
				}
				this.getDateTime2()
				this.getLineInfo()
				// this.onLoad()
			},
			getLine() {
				if(this.dateType == 2) {
					this.dateTime2 = dateFormat(new Date(), 'yyyy-MM-dd')
				}
				getLine(this.gene, this.dateTime2, this.nodeList.join(','), this.dateType).then(res => {
					let isArrs = [] //定义一个空数组
					let isFlag = null //定义一个变量
					res.data.data.forEach(item => {
						let isArr = this._ifFlag(item.yarray) //判断每个站点yarray数组里面的值是否都为0 取反 全部为0 false 反之 true
						isArrs.push(isArr) //选中所有站点
					})
					isFlag = this._isHas(isArrs) //选中所有站点  如果里面有任何一个是ture 则显示报表 否则 暂无数据
					this.isEmpty = isFlag == true ? false : true //暂无数据隐藏 isflag false 则isEmpty true
					if(isFlag) { ////选中所有站点  如果里面有任何一个是ture
						this.chartOptions = {
							tooltip: {
								trigger: 'axis',
								axisPointer: { // 坐标轴指示器，坐标轴触发有效
									type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
								},
							},
							// color: '#1148ff',
							legend: {
								// data: ['站点1', '站点2', '站点3', '站点4']
							},
							grid: {
								left: '3%',
								right: '4%',
								bottom: '3%',
								containLabel: true
							},
							xAxis: [{
								type: 'category',
								data: [],
								axisLabel: {
									interval: this.interval, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
									color: '#ccc'
								},
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false
							}],
							yAxis: {
								type: 'value',
								axisLabel: {
									formatter: '{value} ' + this.unit,
									color: '#333',
								},
								axisLine: {
									lineStyle: {
										color: '#505b83'
									} // x轴坐标轴颜色
								},
								axisTick: false,
								splitLine: {
									show: true,
									lineStyle: {
										color: '#374062',
										type: 'dashed' //设置背景为虚线
									}
								}
							},
							series: []
						}
						this.chartOptions.xAxis[0].data = res.data.data[0].xarray; //x轴数据
						res.data.data.map((item, ind) => {
							this.chartOptions.series.push({
								data: item.yarray,
								type: 'line',
								smooth: 0.5,
								name: item.siteName
							})
						})
					}
				})
			},
			_isHas(arr) {
				return arr.includes(true)
			},
			_ifFlag(arr) {
				return !arr.every(i => i === '') //判断数组里面的值都为0
			}
		}
	};
</script>
<style lang="scss" scoped>
	.empty {
		position: absolute;
		left: 0;
		top: 20%;
		color: #ccc;
		right: 0;
		bottom: 20%;
		margin: auto;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		color: #909399;
	}
	
	.map {
		width: 100%;
		height: 500px;
	}
	
	.box {
		height: 100%;
		margin-bottom: 0;
	}
	
	.search-left {
		display: flex;
		height: 33px;
		line-height: 33px;
	}
	
	.el-row {
		height: calc(100% - 20px);
	}
	
	.el-col {
		height: 100%;
		overflow: auto;
	}
	
	.search-tools {
		height: 49px;
		display: flex;
		justify-content: space-between;
		padding: 0 8px;
	}
	
	.search-right {
		display: flex;
	}
	
	.search-tabs {
		height: 33px;
		display: flex;
		align-items: center;
		margin-right: 40px;
	}
	
	.overlay {
		position: absolute;
		width: 200px;
		height: calc(100% - 35px);
		opacity: 0;
		display: flex;
		align-items: center;
		padding-left: 6px;
		.tree-tool {
			height: 34px;
			width: 18px;
			background: #fff;
			box-shadow: 2px 1px 4px #ccc;
			border-top-right-radius: 3px;
			border-bottom-right-radius: 3px;
			cursor: pointer;
			display: flex;
			padding: 6px 0;
			z-index: 9999;
			.tool-line {
				margin-left: 3px;
				height: 100%;
				border-left: 1px solid #ddd;
			}
		}
	}
	
	.overlay:hover {
		opacity: 1;
	}
</style>